package business;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.CollectivityTeachingPlanWeek;
import orm.CollectivityWeekArrange;
import orm.CollectivityWeekTimeBucket;
import orm.TeachingPlanBaseInfo;
import util.DBHelper;
import util.Utility;
import dao.CTeachingPlanWeekDAO;
import dao.CWeekArrangeDAO;
import dao.CWeekArrangeIDMemoryDAO;
import dao.CWeekTimeBucketDAO;
import dao.TeacherDAO;
import dao.TeachingPlanBaseInfoDAO;


public class CTeachingPlanWeekServlet extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CTeachingPlanWeekServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String strFunc = request.getParameter("func");
		
		if (strFunc == null) {
			return;
		} else if (strFunc.equals("load")) {
			if (request.getAttribute("tpid") == null) {
				com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
				
				String teacherName = teacher.getTname();
				request.setAttribute("teacherName", teacherName);
				
				TeachingPlanBaseInfoDAO tpbiDAO = new TeachingPlanBaseInfoDAO();
				try {
					ArrayList<TeachingPlanBaseInfo> alMonthThemeName = tpbiDAO.getMonthThemeNameByTPProperty();
					ArrayList<TeachingPlanBaseInfo> alWeekThemeName = tpbiDAO.getWeekThemeNameByTPProperty();
					
					request.setAttribute("MonthThemeNameArr", alMonthThemeName);
					request.setAttribute("WeekThemeNameArr", alWeekThemeName);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				request.getRequestDispatcher("../" + Utility.JSP_CollectivityTeachingPlanWeek).forward(request, response);
			} else {
				
			}
		} else if (strFunc.equals("fresh")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			String executionDate = request.getParameter("dateValue");
			
			TeachingPlanBaseInfoDAO tpbiDAO = new TeachingPlanBaseInfoDAO();
			try {
				
				ArrayList<TeachingPlanBaseInfo> alCTPID = tpbiDAO.getCTPIDByExecutionDate(executionDate, teacherID);
				
				Iterator it = alCTPID.iterator();
				
				response.setContentType("text/xml;charset=utf-8");
				StringBuffer sb = new StringBuffer();

				sb.append("<weekDatas>");
				
				Map<String,StringBuffer> datePlanMapping = new LinkedHashMap<String,StringBuffer>();
				
				StringBuffer weekDateNode = null;
				String currentDate = null;
				for(int i = 0; it.hasNext(); i++){
					TeachingPlanBaseInfo tpbi = (TeachingPlanBaseInfo)it.next();
					if(datePlanMapping.get(tpbi.getExecutionDate())==null){
						if(i!=0){
							datePlanMapping.get(currentDate).append("</weekData>");
						}
						weekDateNode = new StringBuffer("<weekData name=\"")
											.append(getDateOfWeek(executionDate,tpbi.getExecutionDate())+1)
											.append("\">");
						datePlanMapping.put(tpbi.getExecutionDate(), weekDateNode);
					}else{
						weekDateNode = datePlanMapping.get(tpbi.getExecutionDate());
					}
					
					weekDateNode.append("<tp>");
					weekDateNode.append("<TPID>"+ tpbi.getTpID() +"</TPID>");
					weekDateNode.append("<ActivityName>" + tpbi.getActivityName() + "</ActivityName>");
					weekDateNode.append("</tp>");
					
					currentDate = tpbi.getExecutionDate();
				}
				int oldLength = sb.length();
				for(StringBuffer ss:datePlanMapping.values()){
					sb.append(ss);
				}
				if(sb.length()>oldLength)
					sb.append("</weekData>");
				
				sb.append("</weekDatas>");
				response.getWriter().write(sb.toString());
				response.getWriter().flush();
				
			} catch (SQLException e) {
				e.printStackTrace();
			}

		} else if (strFunc.equals("save")) {
			CollectivityTeachingPlanWeek ctpw = new CollectivityTeachingPlanWeek();
			ArrayList<CollectivityWeekArrange> alCWA = new ArrayList<CollectivityWeekArrange>();
			ArrayList<CollectivityWeekTimeBucket> alCWTB = new ArrayList<CollectivityWeekTimeBucket>();
			
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CWeekTimeBucketDAO cwtbDAO = new CWeekTimeBucketDAO();
			TeacherDAO teacherDAO = new TeacherDAO();

			pickupFormData(ctpw, request);
			getCollectivityWeekArrangeInsert(alCWA,request);
			getCollectivityWeekTimeBucketInsert(alCWTB,request);
			
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			ctpw.setTeacherID(teacherID);
			insertData(ctpw, alCWA, alCWTB);
			gotoCTPWInfo(request, response);
			
//			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
			response.sendRedirect("CTeachingPlanWeekArrangeFunction?func=toFavor");
		} else if (strFunc.equals("edit")) {
			String strCWeekArrangeID = request.getParameter("CWeekArrangeID");
			
			CollectivityTeachingPlanWeek ctpw = new CollectivityTeachingPlanWeek();
			ArrayList<CollectivityWeekArrange> alCWA = new ArrayList<CollectivityWeekArrange>();
			ArrayList<CollectivityWeekTimeBucket> alCWTB = new ArrayList<CollectivityWeekTimeBucket>();
			
			pickupFormData(ctpw, request);
			getCollectivityWeekArrangeInsert(alCWA, request);
			getCollectivityWeekTimeBucketInsert(alCWTB, request);

			updateData(ctpw, alCWA, alCWTB, strCWeekArrangeID);
			
			gotoCTPWInfo(request, response);
//			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
			response.sendRedirect("CTeachingPlanWeekArrangeFunction?func=toFavor");
		} else if (strFunc.equals("printCTPWeek")) {
			String strCWeekArrangeID = request.getParameter("cWeekArrangeID");
			
			CollectivityWeekTimeBucket[] cwtb = null;
			CollectivityWeekArrange[] cwa = null;
			
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CWeekTimeBucketDAO cwtbDAO = new CWeekTimeBucketDAO();
			TeachingPlanBaseInfoDAO tpbiDAO = new TeachingPlanBaseInfoDAO();
			
			try {
				CollectivityTeachingPlanWeek ctpw = ctpwDAO.getCTPWeekByCWAID(strCWeekArrangeID);
				ArrayList<CollectivityWeekArrange> alCWA = cwaDAO.getCWAByCWAID(strCWeekArrangeID);
				ArrayList<CollectivityWeekTimeBucket> alCWTB = cwtbDAO.getCWTBByCWAID(strCWeekArrangeID);
				ArrayList<TeachingPlanBaseInfo> alMonthThemeName = tpbiDAO.getMonthThemeNameByTPProperty();
				ArrayList<TeachingPlanBaseInfo> alWeekThemeName = tpbiDAO.getWeekThemeNameByTPProperty();
				
				String strThemeActivity = "";
				String strActivityArea = "";
				String strOpenAir = "";
				String strActivitySchedules = "";
				String tpid = null;
				
				cwa = new CollectivityWeekArrange[alCWA.size()];
				for(int k = 0; k < alCWA.size(); k++){
					String activitySchedules = "";
					strActivitySchedules = alCWA.get(k).getActivitySchedules();
					String[] alActivitySchedules = strActivitySchedules.split(",");
					if(alActivitySchedules != null){
						for(int m = 0;m < alActivitySchedules.length; m++){
							tpid = alActivitySchedules[m];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp != null && !temp.equals("")){
								if(!activitySchedules.equals("")){
									activitySchedules+=",";
								}
								activitySchedules += temp;
							}
						}
					}
					cwa[k] = new CollectivityWeekArrange();
					cwa[k].setActivitySchedulesName(activitySchedules);
				}
				
				
//				ArrayList themeActivityName = null;
				cwtb = new CollectivityWeekTimeBucket[alCWTB.size()];
				for(int i = 0; i < alCWTB.size(); i++){
					String themeActivityName = "";
					String activityAreaName = "";
					String openAirName = "";
					
					strThemeActivity = alCWTB.get(i).getThemeActivity();
					strActivityArea = alCWTB.get(i).getActivityArea();
					strOpenAir = alCWTB.get(i).getOpenAir();
					String[] alThemeActivity = strThemeActivity.split(",");
					String[] alActivityArea = strActivityArea.split(",");
					String[] alOpenAir = strOpenAir.split(",");
					if(alThemeActivity != null){
						for(int j = 0; j < alThemeActivity.length; j++){
							tpid = alThemeActivity[j];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp!=null && !temp.equals("")){
								if(!themeActivityName.equals("")){
									themeActivityName+=",";
								}
								themeActivityName += temp;
							}
						}
					}
					cwtb[i] = new CollectivityWeekTimeBucket();
					cwtb[i].setThemeActivityName(themeActivityName);
					
					
					if(alActivityArea != null){
						for(int j = 0; j < alActivityArea.length; j++){
							tpid = alActivityArea[j];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp!=null && !temp.equals("null")){
								if(!activityAreaName.equals("")){
									activityAreaName+=",";
								}
								activityAreaName += temp;
							}
						}
					}
					cwtb[i].setActivityAreaName(activityAreaName);
					if(alOpenAir != null){
						for(int j = 0; j < alOpenAir.length; j++){
							tpid = alOpenAir[j];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp!=null && !temp.equals("")){
								if(!openAirName.equals("")){
									openAirName+=",";
								}
								openAirName += temp;
							}
						}
					}
					cwtb[i].setOpenAirName(openAirName);
				}
				
				request.setAttribute("CTPW", ctpw);
				request.setAttribute("CWAArr", alCWA);
				request.setAttribute("CWTBArr", alCWTB);
				request.setAttribute("CWTBNames", cwtb);
				request.setAttribute("CWANames", cwa);
				request.setAttribute("MonthThemeNameArr", alMonthThemeName);
				request.setAttribute("WeekThemeNameArr", alWeekThemeName);
					
				request.getRequestDispatcher("../" + 
							Utility.JSP_PrintCTPWeek).forward(request, response);
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else if(strFunc.equals("toFavor")){
			gotoCTPWInfo(request, response);
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
		}
	}
	public static int getDateOfWeek(String monthday,String currentday){
		if(monthday.indexOf(" ")!=-1)
			monthday = monthday.substring(0, monthday.indexOf(" "));
		if(currentday.indexOf(" ")!=-1)
			currentday = currentday.substring(0, currentday.indexOf(" "));
		String[] dataParts1 = monthday.split("-");
		String[] dataParts2 = currentday.split("-");
		Calendar c = Calendar.getInstance();
		c.set(new Integer(dataParts1[0]), new Integer(dataParts1[1])-1, new Integer(dataParts1[2]));
		Calendar c2 = Calendar.getInstance();
		c2.set(new Integer(dataParts2[0]), new Integer(dataParts2[1])-1, new Integer(dataParts2[2]));
		long ss = c2.getTime().getTime() - c.getTime().getTime();
		double dd = ss;
		return dd/1000/60/60/24>ss/1000/60/60/24?((int)ss/1000/60/60/24)+1:((int)ss/1000/60/60/24);
	}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void pickupFormData(CollectivityTeachingPlanWeek ctpw, HttpServletRequest request) {		
		ctpw.setClassID(request.getParameter("ClassID"));
		ctpw.setExecutionDate(request.getParameter("txtExecutionDate"));
		ctpw.setExecutionWeek(request.getParameter("ExecutionWeek"));
		ctpw.setMonthThemeName(request.getParameter("MonthThemeName"));
		ctpw.setWeekThemeName(request.getParameter("WeekThemeName"));
		ctpw.setWeekTarget(request.getParameter("WeekTarget"));
		ctpw.setStartDate(request.getParameter("StartDate"));
		ctpw.setConstitutor(request.getParameter("Constitutor"));

	}
	
	public void getCollectivityWeekArrangeInsert(ArrayList<CollectivityWeekArrange> cwaArr, HttpServletRequest request){
		for(int weekID = 1; weekID < 6; weekID++){
			CollectivityWeekArrange cwa = new CollectivityWeekArrange();
			String strCWeekArrangeID = request.getParameter("CWeekArrangeID");
			cwa.setCWeekArrangeID(strCWeekArrangeID);
			cwa.setWeekID(weekID);
			
			String[] strActivitySchedules = request.getParameterValues("ActivitySchedules"+weekID);
			StringBuffer sbActivitySchedules = new StringBuffer();
			if(strActivitySchedules != null){
				for(int a = 0; a < strActivitySchedules.length; a++){
					sbActivitySchedules.append(strActivitySchedules[a]);
					if(a != strActivitySchedules.length){
						sbActivitySchedules.append(",");
					}
				}
			}
			cwa.setActivitySchedules(sbActivitySchedules.toString());
			cwa.setRemark(request.getParameter("Remark" + weekID));
			cwaArr.add(cwa);
		}
	}

	public void getCollectivityWeekTimeBucketInsert(ArrayList<CollectivityWeekTimeBucket> cwtbArr, HttpServletRequest request){
		for(int weekID = 1; weekID < 6; weekID++){
			
			for(int timeBucketID = 1; timeBucketID < 4; timeBucketID++){
				CollectivityWeekTimeBucket cwtb = new CollectivityWeekTimeBucket();
				String strCWeekArrangeID = request.getParameter("CWeekArrangeID");
				cwtb.setCWeekArrangeID(strCWeekArrangeID);
				cwtb.setWeekID(weekID);
				
				cwtb.setTimeBucketID(timeBucketID);
				
				String[] strThemeActivity = request.getParameterValues("ThemeActivity"+weekID+timeBucketID);
				StringBuffer sb = new StringBuffer();
				if(strThemeActivity != null){
					for(int i = 0; i < strThemeActivity.length; i++){
						sb.append(strThemeActivity[i]);
						if(i != strThemeActivity.length -1){
							sb.append(",");
						}
					}
				}
				cwtb.setThemeActivity(sb.toString());

				String[] strActivityArea = request.getParameterValues("ActivityArea"+weekID+timeBucketID);
				StringBuffer sbActivityArea = new StringBuffer();
				if(strActivityArea != null){
					for(int j = 0; j < strActivityArea.length; j++){
						sbActivityArea.append(strActivityArea[j]);
						if(j != strActivityArea.length - 1){
							sbActivityArea.append(",");
						}
					}
				}
				cwtb.setActivityArea(sbActivityArea.toString());
				
				String[] strOpenAir = request.getParameterValues("OpenAir"+weekID+timeBucketID);
				StringBuffer sbOpenAir = new StringBuffer();
				if(strOpenAir != null){
					for(int k = 0; k < strOpenAir.length; k++){
						sbOpenAir.append(strOpenAir[k]);
						if(k != strOpenAir.length - 1){
							sbOpenAir.append(",");
						}
					}
				}
				cwtb.setOpenAir(sbOpenAir.toString());
				
				cwtbArr.add(cwtb);
			}
		}
	}

	public void insertData(CollectivityTeachingPlanWeek ctpw, ArrayList<CollectivityWeekArrange> cwaArr, 
			ArrayList<CollectivityWeekTimeBucket> cwtbArr) {
		Connection conn = DBHelper.getConnection();
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			conn.setAutoCommit(false);
			
			CWeekArrangeIDMemoryDAO cwaIDMemDAO = new CWeekArrangeIDMemoryDAO();
			int nCWeekArrangeID = cwaIDMemDAO.increaseCWeekArrangeID(stmt);
			String cWeekArrangeID = "CWeek" + nCWeekArrangeID;
			
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			ctpw.setCWeekArrangeID(cWeekArrangeID);
			ctpwDAO.insertCTPWeek(stmt, ctpw);
			
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			
			cwaDAO.insertCWeekkArrange(stmt, cwaArr, cWeekArrangeID);
			
			CWeekTimeBucketDAO cwtbDAO = new CWeekTimeBucketDAO();
			cwtbDAO.insertCWeekTimeBucket(stmt, cwtbArr, cWeekArrangeID);

			conn.commit();
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException ee) {
				ee.printStackTrace();
			}
		}
	}
	
	public void updateData(CollectivityTeachingPlanWeek ctpw, ArrayList<CollectivityWeekArrange> cwaArr,
			ArrayList<CollectivityWeekTimeBucket> cwtbArr, String cWeekArrangeID) {
		Connection conn = DBHelper.getConnection();
		Statement stmt = null;
		
		try {
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			ctpw.setCWeekArrangeID(cWeekArrangeID);
			ctpwDAO.updateCTPWeek(stmt, ctpw);
			
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			cwaDAO.updateCWeekkArrange(stmt, cwaArr, cWeekArrangeID);
			
			CWeekTimeBucketDAO cwtbDAO = new CWeekTimeBucketDAO();
			cwtbDAO.updateCWeekTimeBucket(stmt, cwtbArr, cWeekArrangeID);
			
			conn.commit();
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException ee) {
				
			}
		}
	}
	
	public void gotoCTPWInfo(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException{
		CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
		CollectivityTeachingPlanWeek ctpw = null;
		TeacherDAO teacherDAO = new TeacherDAO();
		
		com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
		
		Integer teacherID = teacher.getTeacherId();

		try {
			request.setAttribute("pageNo", 1);
			int PageSize = Utility.PageSize;
			ArrayList al = ctpwDAO.getAllCTeachingPlanWeek(teacherID);
			int totalPage = 0;
			if (al.size() % PageSize == 0) {
				totalPage = al.size()/PageSize;
				request.setAttribute("totalPage",totalPage);
			} else {
				totalPage = (al.size()/PageSize) + 1;
				request.setAttribute("totalPage",totalPage);
			}
	
			al = new ArrayList<CollectivityTeachingPlanWeek>();
			ListIterator<CollectivityTeachingPlanWeek> it = ctpwDAO.getAllCTeachingPlanWeek(teacherID).listIterator();
			int ii = 0;
			while (it.hasNext()) {
				CollectivityTeachingPlanWeek t = it.next();
				
				ctpw = new CollectivityTeachingPlanWeek();
				ctpw.setCWeekArrangeID(t.getCWeekArrangeID());
				ctpw.setMonthThemeName(t.getMonthThemeName());
				ctpw.setWeekThemeName(t.getWeekThemeName());
				ctpw.setConstitutor(t.getConstitutor());
				ctpw.setClassID(t.getClassID());
				ctpw.setExecutionDate(t.getExecutionDate());
				
				al.add(ctpw);
				ii++;

				if(ii > (PageSize-1)) {
					break;
				}
			}
			request.setAttribute("CTPWList", al);	
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	}
	public static void main(String[] arsg){
		String dates = "2009-05-29";
		
		System.out.println(getDateOfWeek(dates,"2009-06-2"));
//		String[] dataParts = dates.split("-");
//		Calendar c = Calendar.getInstance();
//		c.set(new Integer(dataParts[0]), new Integer(dataParts[1])-1, new Integer(dataParts[2]));
//		c.add(Calendar.DAY_OF_MONTH, 4);
//		System.out.println(c.getTime());
//		System.out.println(c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH));
	}
}
